CREATE PROCEDURE Role_FindAll
AS
BEGIN
    Select 
    RoleId,
    ApplicationId,
    RoleName
    from Role
END
GO

CREATE PROCEDURE Role_FindById
@RoleId int
AS
BEGIN
    Select * from Role where RoleId = @RoleId
END
GO

CREATE PROCEDURE Role_FindByName
@name nvarchar(50)
AS
BEGIN
    Select * from Role where RoleId = @name
END
GO

CREATE PROCEDURE Role_Insert
        @RoleId int ,
        @ApplicationId int ,
        @RoleName nvarchar (50)
AS
BEGIN
INSERT INTO Role
(
        RoleId,
        ApplicationId,
        RoleName
)
VALUES
(
        @RoleId,
        @ApplicationId,
        @RoleName
)
select @RoleId = @@IDENTITY
END
GO

CREATE PROCEDURE Role_Update
        @RoleId int ,
        @ApplicationId int ,
        @RoleName nvarchar (50),
AS
BEGIN
UPDATE  Role SET
    ApplicationId = @ApplicationId,
    RoleName = @RoleName
    WHERE RoleId = @RoleId
END
GO

CREATE PROCEDURE Role_Delete
    @RoleId int
AS
BEGIN
    DELETE FROM Role where RoleId = @RoleId
END
GO

CREATE PROCEDURE Role_Paging
    @PageSize int, 
    @PageNumber int
    AS 
    declare @RowStart int
    declare @RowEnd int
    if @PageNumber > 0 
    BEGIN	
    set @PageNumber = @PageNumber - 1
    set @RowStart = @PageSize * @PageNumber + 1;
    set @RowEnd = @RowStart  + @PageSize - 1;
    SELECT TotalRowCount = COUNT(RoleId) FROM Role;
    WITH MyTable as 
    (
    SELECT * ,  ROW_NUMBER() OVER (order by SortIndex) as RowNumber From  Role
    )
    SELECT * from MyTable where RowNumber >= @RowStart and RowNumber <= @RowEnd
END
GO

CREATE proc Role_SetActive
@RoleId int
AS
declare @Type bit
SELECT @Type =  IsActive from Role where RoleId = @RoleId
BEGIN
IF(@Type = 1)
Update Role set IsActive = 0 where RoleId = @RoleId
else
Update Role set IsActive = 1 where RoleId = @RoleId
END
GO

CREATE proc Role_SetSortIndex
@RoleId int, 
@Type int
AS
declare @CurrentSort int
select @CurrentSort = SortIndex from  Role where RoleId = @RoleId
BEGIN
IF(@Type = 1)
Update Role set SortIndex =  @CurrentSort + 1 where RoleId = @RoleId
else
Update Role set SortIndex =  @CurrentSort - 1 where RoleId = @RoleId
END
GO

CREATE PROCEDURE Role_RemoveSelectedItem
    @RoleId int
AS
BEGIN
    UPDATE Role SET IsDeleted = 1 WHERE RoleId = @RoleId
END
GO

CREATE PROCEDURE Role_RestoreSelectedItem
    @RoleId int
AS
BEGIN
    UPDATE Role SET IsDeleted = 0 WHERE RoleId = @RoleId
END
GO

CREATE PROCEDURE Role_RemoveAll
    @RoleId int
AS
BEGIN
    UPDATE Role SET IsDeleted = 1
END
GO

CREATE PROCEDURE Role_RestoreAll
    @RoleId int
AS
BEGIN
    UPDATE Role SET IsDeleted = 0
END
GO

